package Server_Netty;

import Server_Netty.TCP.TCPServer;
import Server_Netty.UDP.UDPServer;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main_Send_Receive_Manager {
    //创建Logger对象
    public static final Logger LOGGER = LoggerFactory.getLogger(Main_Send_Receive_Manager.class);

    //定义通道标识号
    public static int Channel_RoleID_1=6501;
    public static int Channel_RoleID_2=6502;
    public static int Channel_RoleID_3=6503;
    public static int Channel_RoleID_4=6504;

    //创建存放 通道号、TCP服务类对象、接收的TCP数据包 的容器
    public  static Map<Integer, ChannelHandlerContext> RoleID_map = new HashMap<Integer, ChannelHandlerContext>();
    public  static Map<Integer, TCPServer> RoleID_TCPServer = new HashMap<Integer, TCPServer>();
    public  static Map<Integer, UDPServer> RoleID_UDPServer = new HashMap<Integer, UDPServer>();
    public  static Map<Integer, LinkedBlockingQueue<DataCallBackClass>> RoleID_ReceiveQueue= new HashMap<Integer, LinkedBlockingQueue<DataCallBackClass>>();

    public Main_Send_Receive_Manager() {
    }
    public Main_Send_Receive_Manager(int Channel_1,int Channel_2,int Channel_3,int Channel_4) {
        Channel_RoleID_1=Channel_1;
        Channel_RoleID_2= Channel_2;
        Channel_RoleID_3=Channel_3;
        Channel_RoleID_4= Channel_4;
        LOGGER.info(Channel_RoleID_1+","+Channel_RoleID_2+","+Channel_RoleID_3+","+Channel_RoleID_4);
    }

    //启动数据接收/发送服务端
    public boolean ServerStart(String[] Connect_Way, int[] RoleID, String[] local_address, int[] port) throws Exception {
        AtomicBoolean bOk= new AtomicBoolean(false);
        for ( int temp_i=0;temp_i<RoleID.length;temp_i++) {
            int Temp_RoleID=RoleID[temp_i];
            Start_Server_Thread start_server_thread=new Start_Server_Thread(Connect_Way[temp_i], Temp_RoleID, local_address[temp_i], port[temp_i]);
            start_server_thread.start();
        }
        return bOk.get();
    }

    //启动数据接收/发送服务端
    public static void ServerStart(int RoleID,String Connect_Way,String local_address, int port) throws Exception {
        int Temp_RoleID=RoleID;
        Start_Server_Thread start_server_thread=new Start_Server_Thread(Connect_Way,Temp_RoleID, local_address, port);
        start_server_thread.start();
    }

    //关闭服务端
    public static void StopServer(int Server_RoleID){
        if (RoleID_map.get(Server_RoleID)!=null){
            //RoleID_map.get(Server_RoleID).channel().close();
            RoleID_map.get(Server_RoleID).channel().eventLoop().shutdownGracefully();
            RoleID_map.remove(Server_RoleID);
            if (RoleID_TCPServer.get(Server_RoleID)!=null){
                RoleID_TCPServer.remove(Server_RoleID);
            }
        }
    }
}
